<?php
ini_set('max_execution_time', 0);
header('Content-Type:text/html;charset=utf8');
include_once './db_orm.php';
include_once './function.php';
include_once './simple_html_dom.php';

use Illuminate\Database\Capsule\Manager as DB;

$db_table = 'm_bn_postlist';
$keyword_url = "diqu114.com";

$work = DB::table('work')->select('id', 'cpid')->where('update_time', null)->orderBy('id')->first();
if (empty($work)) {
    echo '没有任务';
    die();
}

$type = explode(',', $work['type']);
$cpid = $work['cpid'];

$res = $db->getAll("select `id`,`searchkey` from " . $db_table . " where `cpid` = $cpid order by id");

if (!empty($type)) {//自定义搜索引擎

    $insert_data = array();
    foreach ($res as $value) {
        if (in_array('baidu', $type)) {
            $insert_data['baidurank'] = getRank($value['searchkey'], $keyword_url, $value['id'], 1);
        }
        if (in_array('sogou', $type)) {
            $insert_data['sogourank'] = getRank($value['searchkey'], $keyword_url, $value['id'], 2);
        }
        if (in_array('360', $type)) {
            $insert_data['360rank'] = getRank($value['searchkey'], $keyword_url, $value['id'], 4);//360
        }
        if (in_array('sm', $type)) {
            $insert_data['smrank'] = getRank($value['searchkey'], $keyword_url, $value['id'], 3);
        }
        if (in_array('baidum', $type)) {
            $insert_data['baidumrank'] = getRank($value['searchkey'], $keyword_url, $value['id'], 5);//baidu_m
        }
        $insert_data['update_time'] = time();
        $db->update($db_table,
            $insert_data,
            'id = ' . $value['id']);
        echo $value['id'] . "排名成功" . "\n";
    }
} else {//所有搜索引擎

    foreach ($res as $value) {
        $baidu_rank = getRank($value['searchkey'], $keyword_url, $value['id'], 1);
        $sogou_rank = getRank($value['searchkey'], $keyword_url, $value['id'], 2);
        $smrank = getRank($value['searchkey'], $keyword_url, $value['id'], 3);
        $sorank = getRank($value['searchkey'], $keyword_url, $value['id'], 4);//360
        $mbaidurank = getRank($value['searchkey'], $keyword_url, $value['id'], 5);//baidu_m
//        var_dump($sorank);
//        exit;
        $db->update($db_table,
            array(
                'baidurank' => $baidu_rank,
                'sogourank' => $sogou_rank,
                '360rank' => $sorank,
                'smrank' => $smrank,
                'baidumrank' => $mbaidurank,
                'update_time' => time(),
            ),
            'id = ' . $value['id']);
        echo $value['id'] . "排名成功" . "\n";
    }
}

//任务完成修改时间
$db->update('work', ['update_time' => time()], "id = " . $work['id']);
echo 'success';